package com.atguigu.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {
    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

    /*
    [
        { id:'031', name:'n3.n1', isParent:true},
        { id:'032', name:'n3.n2', isParent:false},
        { id:'033', name:'n3.n3', isParent:true},
        { id:'034', name:'n3.n4', isParent:false}
     ]
     */

    @Override
    public List<Map<String, Object>> findZnodes(Long parentId) {
        //按照parentId查询下级字典项列表List<Dict>
        List<Dict> dictList = this.dictDao.findZnodes(parentId);
        //将List<Dict>转换为List<Map<String, Object>>
        List<Map<String, Object>> zNodes = new ArrayList<>();
        for(Dict dict:dictList){
            Map<String, Object> node = new HashMap();
            node.put("id",dict.getId());
            node.put("name",dict.getName());
            Integer count = dictDao.countIsParent(dict.getId());
            node.put("isParent",count>0?true:false);

            zNodes.add(node);
        }
        //返回List<Map<String, Object>>
        return zNodes;
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //根据dictCode找到Id
        Dict dict = dictDao.getByDictCode(dictCode);
        //使用id作为parentId查询下级字典项列表
        List<Dict> dictList = this.dictDao.findZnodes(dict.getId());
        return dictList;
    }

    @Override
    public List<Dict> findListByParentId(Long parentId) {
        //按照parentId查询下级字典项列表List<Dict>
        List<Dict> dictList = this.dictDao.findZnodes(parentId);
        return dictList;
    }

    @Override
    public String getNameById(Long dictId) {
         return   this.dictDao.getNameById(dictId);
    }
}
